package com.atguigu.lease.common.Redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;


@Configuration
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        //这是创建RedisTemplate对象的关键，它提供了与Redis交互的模板功能。
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        //设置RedisConnectionFactory，用于连接Redis服务器
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //创建JSON序列化器，用于序列化和反序列化Redis中的对象
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();

        //设置key的序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());

        //设置value的序列化
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        //返回RedisTemplate对象
        return redisTemplate;
    }
}
